<?php

/**
 * This file is part of the Pagizer package.
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @copyright   Copyright (c) 2010 Advisa (http://www.advisa.fr)
 * @author      Pagizer Core Team <team@pagizer.org>
 * @package     pagizer
 * @subpackage  website
 */

/**
 * This patch will remove old image links and change them to the mediaUrl smarty tag
 */
class core_module_website_0_3_3_Patch001 extends f_package_Patch
{
    public function patch()
    {
        $freeContents = f_document_Provider::getInstance()->loadDocuments('modules_website/freeContent')->retrieveDocuments('*');

        if(count($freeContents) > 0)
        {
            foreach($freeContents as $freeContent)
            {
                $content = $freeContent->getContent();

                preg_match_all('/<img.*id="(.*?)".*src="(.*?)\?.*?".*\/>/',$content, $matches);

                if(count($matches[0]) > 0)
                {
                    foreach($matches[0] as $k => $tag)
                    {
                        if(preg_match('/picture_.*?/', $matches[1][$k]))
                        {
                            list($prefix,$id) = explode('_', $matches[1][$k]);
                            $src = $matches[2][$k];

                            if(!preg_match('/{{.*}}/', $src))
                            {
                                $exp = explode('/', $src);
                                $fileName = end($exp);

                                $newSrc = '{{mediaUrl docId='.$id.' fileName=\''.$fileName.'\'}}';
                                $content = str_replace($src, $newSrc, $content);
                                $freeContent->setContent($content)->save();
                            }
                        }
                    }
                }
            }
        }
    }  
}